<?php

/**
 * This is the model class for table "goods".
 *
 * The followings are the available columns in table 'goods':
 * @property string $id 产品id
 * @property string $goods_name Goods Name
 * @property string $remark 商品简介
 * @property string $img_path 商品主图
 * @property string $object_type Object Type
 */
class Goods extends ContentBase
{
	const TYPE_NATIVE = 4;
	const TYPE_TRAVEL = 1;
	const TYPE_TICKET = 5;
	const TYPE_TICKET_TRAIN = 6;
	const TYPE_SCENIC = 3;
	const TYPE_HOTEL = 2;
	
	protected function beforeValidate() {
		$this->class_id = $this->config->class_id;
		return parent::beforeValidate();
	}
	
	public function getMdcClass() {
        return 'application.models.metadata.GoodsMetadata';
    }
	
	public function listing() {
		$criteria = $this->getDbCriteria();
		$criteria->select = 't.*';
//		$criteria->join = 'left join v_goods_agentable as v on (t.id = v.goods_id)';
		$criteria->compare('t.listing_status','ST_LISTING');
		$criteria->compare('t.status','ST_PASSED');
//		$criteria->addCondition('v.id IS NOT NULL');
		$criteria->group = 't.id';
		$criteria->order = 't.listing_time desc';
		return $this;
	}
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Goods the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
	
	/**
	 * 是否可以购买商品
	 * Enter description here ...
	 */
	public function isBuyAble() {
		return Yii::app()->adminUser->role == AdminUser::ROLE_MEMBER;
	}
	
	/**
	 * 是否可以查看代理价
	 * Enter description here ...
	 */
	public function isAgentAble() {
		$adminUser = Yii::app()->adminUser;
		if(!empty($adminUser->id) && $adminUser->role == AdminUser::ROLE_DEALER) {
			$related = AgentRelated::model()->related($adminUser->id, $this->provider_id);
			if (CHtml::value($related, 'status') == 'ST_PASSED') {
				return true;
			}			
		} else if(!empty($adminUser->id) && $adminUser->role == AdminUser::ROLE_PROVIDER) {
			$relateds = CategoryAgentRelated::model()->findAllByAttributes(array('provider_id'=>$adminUser->id,'status'=>'ST_PASSED'));
			$relatedsIds = CHtml::listData($relateds, 'category_id', 'category_id');
			if (in_array($this->class_id, $relatedsIds)) {
				return true;
			}
		}
		return false;
	}
	
	public function isAgentGoodsAble() {
		$adminUser = Yii::app()->adminUser;
		if(!empty($adminUser->id) && $adminUser->role == AdminUser::ROLE_DEALER) {
			$related = AgentRelated::model()->related($adminUser->id, $this->provider_id);
			if (CHtml::value($related, 'status') == 'ST_PASSED') {
				return true;
			}			
		}
		return false;
	}
}